package vashion.azeroth.api.core.filter;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import vashion.azeroth.common.net.IpUtil;

public class FilterLog implements Filter {

	private final static Logger log = LoggerFactory.getLogger(FilterLog.class);

	@Override
	 public void init(FilterConfig arg0) throws ServletException {}
	
	@Override
	public void destroy() {}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
//		req.setCharacterEncoding("UTF-8");
		res.setHeader("Cache-Control", "no-cache");
		res.setHeader("Pragma", "no-cache");
		res.setDateHeader("Expires", 0);
//		res.setCharacterEncoding("UTF-8");
		createLog(req);
		chain.doFilter(req, res);
	}

	@SuppressWarnings("unchecked")
	private void createLog(HttpServletRequest req) {
		StringBuilder bufMsg = new StringBuilder();
	    bufMsg.append("{IP:")
	          .append(IpUtil.getIpAddress(req))
	          .append(",")
	          .append("urlStr:")
	          .append(req.getRequestURI())
	          .append(",params:{");
	    
		Map paraMap = req.getParameterMap();
		Iterator it = paraMap.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String key = (String) entry.getKey();
			String[] values = (String[])entry.getValue();
			String value= "[";
			for(String v : values){
				value += v+",";
			}
			value =(value.length()>1?value.substring(0,value.length()-1):value)+ "]";
			bufMsg.append(key).append(":").append(value).append(",");
		}
		String result =(paraMap.size()>0? bufMsg.substring(0, bufMsg.length()-1):bufMsg)+"}}";
		log.info(result);
	}

}
